var BagController = pc.createScript("bagController");

var useTouch = false;

BagController.prototype.initialize = function () {
    if (useTouch) {
        // 注册Touch事件
        this.touchBeginListener = this.touchBegin.bind(this);
        window.addEventListener('touchstart', this.touchBeginListener, false);
        window.addEventListener('mousedown', this.touchBeginListener, false);

        this.touchMoveListener = this.touchMove.bind(this);
        window.addEventListener('touchmove', this.touchMoveListener, false);
        window.addEventListener('mousemove', this.touchMoveListener, false);

        this.touchEndListener = this.touchEnd.bind(this);
        window.addEventListener('touchend', this.touchEndListener, false);
        window.addEventListener('mouseup', this.touchEndListener, false);

        this.touchCancelListener = this.touchEnd.bind(this);
        window.addEventListener('touchcancel', this.touchCancelListener, false);
    } else if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', function (event) {
            var alpha = event.alpha;
            var beta = event.beta;
            var gamma = event.gamma;

            // var a = document.getElementById('alpha');
            // var b = document.getElementById('beta');
            // var g = document.getElementById('gamma');
            // a.innerHTML = Math.round(alpha);
            // b.innerHTML = Math.round(beta);
            // g.innerHTML = Math.round(gamma);

            this.entity.setEulerAngles(beta, gamma, 0);

        }, false);
    } else {
        document.querySelector('body').innerHTML = '你的浏览器不支持陀螺仪';
    }


    this.isTouchBegin = false;
    this.dx = 0;
    this.dy = 0;
    this.lastTouchX = 0;
    this.lastTouchY = 0;
};

BagController.prototype.update = function (dt) {

};

BagController.prototype.touchBegin = function (event) {
    this.isTouchBegin = true;
    if (isMobile) {
        this.lastTouchX = event.touches[0].clientX;
        this.lastTouchY = event.touches[0].clientY;
    }
};

BagController.prototype.touchMove = function (event) {
    if (this.isTouchBegin) {
        if (isMobile) {
            if (event.touches.length == 1) {
                this.dx = event.touches[0].clientX - this.lastTouchX;
                this.dy = event.touches[0].clientY - this.lastTouchY;
                this.lastTouchX = event.touches[0].clientX;
                this.lastTouchY = event.touches[0].clientY;

                this.entity.rotateLocal(this.dy, this.dx, 0);
            } else if (event.touches.length == 2) {

            }
        } else {
            this.dx = event.dx;
            this.dy = event.dy;
            this.entity.rotateLocal(this.dy, this.dx, 0);
        }
    }
};

BagController.prototype.touchEnd = function (event) {
    this.isTouchBegin = false;
};